<template>
    <div class="article-list">
        <van-pull-refresh
            v-model="isRefreshLoading"
            @refresh="onRefresh"
            :success-text="refreshSuccessText"
            :success-duration="1500">
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                :error.sync="error"
                error-text="请求失败，点击重新加载"
                @load="onLoad"
            >
          <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.title" /> -->
          <ArticleItem v-for="(item,index) in list" :key="index+'012'" :article="item" ></ArticleItem>
        </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 文章列表数据
      loading: false, // 上拉加载更多
      finished: false, // 是否加载结束
      error: false,
      timestamp: null, // 请求下一页数据的时间戳
      isRefreshLoading: false,
      refreshSuccessText: ''
    }
  },
  components: {
    ArticleItem
  },
  mounted () {
    // console.log(this.list)
  },

  methods: {
    async onLoad () {
      // console.log(this.list)
      // 异步更新数据
      try {
        // 1.请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道id
          timestamp: this.timestamp || Date.now(),
          with_top: 1 // 是否包含置顶 进入页面第一次要求置顶 1-包含 0-不包含
        })
        // 2.数据添加进list数组
        const { results } = data.data
        this.list.push(...results)
        // console.log(this.list)
        // 3. 设置本次加载中 loading 状态结束
        this.loading = false
        // 4. 判断数据是否加载结束
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
        this.loading = false // 关闭loading效果
        this.error = true // 开启错误提示
      }
    },
    async onRefresh () {
      try {
        // 1. 请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道id
          timestamp: this.timestamp || Date.now(),
          with_top: 1 // 是否包含置顶 进入页面第一次要求置顶 1-包含 0-不包含
        })
        // 2. 将数据追加到列表的顶部
        const { results } = data.data
        this.list.unshift(...results)
        // console.log(this.list)
        // 3. 关闭下拉刷新 loading 状态结束
        this.isRefreshLoading = false
        // 提示成功
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        console.log(err)
        this.isRefreshLoading = false // 关闭下拉刷新
        this.$toast('刷新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-list{
    height: 79vh;
    overflow: auto;
}
</style>
